#include "widget.h"
#include "ui_widget.h"
#include <QHostAddress>

const QString& SERVER_IP = "127.0.0.1";
const quint16 SERVER_PORT = 9090;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 1.设置窗口标题
    this->setWindowTitle("客户端");
    // 2.获取tcpSocket实例 -- 添加到对象树
    socket = new QTcpSocket(this);
    // 3.连接信号槽，处理服务器响应
    connect(socket, &QTcpSocket::readyRead, this, [&](){
        // 1.接收响应
        QString response = socket->readAll();
        // 2.打印日志
        QString log = "服务器说: " + response;
        ui->listWidget->addItem(log);
    });
    // 4.与服务器建立连接 -- Qt中的connect是非阻塞的
    socket->connectToHost(SERVER_IP, SERVER_PORT);
    // 5.等待连接建立成功 -- 阻塞方式等待
    socket->waitForConnected();

}

Widget::~Widget()
{
    delete ui;
}

// 发送请求
void Widget::on_pushButton_clicked()
{
    // 1.获取输入框数据
    QString request = ui->lineEdit->text();
    // 2.清空输入框
    ui->lineEdit->setText("");
    // 3.打印日志
    QString log = "客户端说: " + request;
    ui->listWidget->addItem(log);
    // 4.发送请求
    socket->write(request.toUtf8());
}
